package com.hellloop.pim.alphabeat.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class DummyServer {

	private static final int DEFAULT_PORT_NUMBER = 44215;

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		DummyConnectionThread proxy = new DummyConnectionThread(
				DEFAULT_PORT_NUMBER);

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			String line = br.readLine();
			if (line != null) {
				
				if (line.equals("exit")) {
					System.out.println("Terminate.");
					System.exit(0);
				} else if (line.length() > 4
						&& line.substring(0, 4).equals("send")) {
					String[] tkn = line.split(" ");
					if(tkn.length != 2) {
						System.err.println("[Usage] send <message in PIMMessage format>");
					}
					
					//proxy.sendMessage(tkn[1].replaceAll(",", PIMMessage));

				}
			}
		}
	}

}

class DummyConnectionThread extends Thread {

	private PrintWriter writer;

	private BufferedReader reader;
	private Socket clientSocket;

	DummyConnectionThread(int port) throws IOException {
		ServerSocket servSock = new ServerSocket(port);
		System.out.println("Open connection at port: " + port);
		clientSocket = servSock.accept();
		System.out.println("Receive connection from: "
				+ clientSocket.getInetAddress().getHostName() + " at port "
				+ clientSocket.getPort());

		this.writer = new PrintWriter(clientSocket.getOutputStream(), true);
		this.reader = new BufferedReader(new InputStreamReader(clientSocket
				.getInputStream()));

		this.start();
	}

	public void run() {

		while (true) {
			String line;
			try {
				if ((line = reader.readLine()) != null) {
					System.out.println("receiveMessage: " + line);
				}
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(0);
			}

			// Do some sleep
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void sendMessage(String message) {
		this.writer.println(message);
	}

}